package com.im.partchat.mvp.persenter;

import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;

import com.im.partchat.App;
import com.im.partchat.base.IBaseView;
import com.im.partchat.bean.Department;
import com.im.partchat.bean.Group;
import com.im.partchat.bean.User;
import com.im.partchat.bean.UserBean;
import com.im.partchat.bean.reponsed.BaseResponse;
import com.im.partchat.db.dao.DeptDao;
import com.im.partchat.db.dao.UserDao;
import com.im.partchat.mvp.model.login.LoginModel;
import com.im.partchat.mvp.model.login.LoginModelImpl;
import com.im.partchat.utils.rxlifecycle.compact.RxLifecycleCompact;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;

/**
 * Created by fzl on 2017/6/28 0028.
 * VersionCode: 1
 * Desc:
 */

public class LoginPresenter extends BasePresenter {
    public static final String TAG="LoginPresenter";
    private IBaseView<List<Group>> baseView;
    private LoginModel loginModel;
    private AppCompatActivity context;

    public LoginPresenter(IBaseView<List<Group>> baseView, AppCompatActivity activity) {
        this.loginModel = new LoginModelImpl();
        this.baseView = baseView;
        this.context = activity;
    }

    public void login(String userName, String password) {
        baseView.showLoading("正在登陆……");
        Observable<UserBean> filterLogin = loginServer(userName, password);
        Observable<List<Department>> filterDepartment = updateDepartment(filterLogin);
        Observable<List<User>> filterUser = updateUser(filterDepartment);
        Observable<List<Group>> filterGroup = getGroupList(filterUser);
        filterGroup.compose(RxLifecycleCompact.bind(context).<List<Group>>withObservable())

                .subscribe(new Observer<List<Group>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<Group> value) {
                        baseView.onLoadDataSuccess(value, "");



                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        baseView.showError(NetErrorObservable(e));
                        baseView.hideLoading();
                    }

                    @Override
                    public void onComplete() {
                        baseView.hideLoading();
                    }
                });


    }

    private Observable<UserBean> loginServer(String userName, String password) {
        return loginModel.login(userName, password)
                .map(new Function<BaseResponse<UserBean>, UserBean>() {
                    @Override
                    public UserBean apply(BaseResponse<UserBean> userBaseResponse) throws Exception {
                        if (userBaseResponse.getCode().equals("1")) {
                            return userBaseResponse.getData();
                        } else {
                            String msg = userBaseResponse.getMsg();
                            if (TextUtils.isEmpty(msg)) {
                                msg = "用户名或密码有误";
                            }
                            baseView.hideLoading();
                            baseView.showError(msg);
                            return new UserBean();
                        }
                    }
                }).filter(new Predicate<UserBean>() {
                    @Override
                    public boolean test(UserBean userBean) throws Exception {
                        return userBean != null&&!TextUtils.isEmpty(userBean.getId());
                    }
                });
    }


    public Observable<List<Department>> updateDepartment(Observable<UserBean> filterUser) {
        return filterUser.flatMap(new Function<UserBean, Observable<BaseResponse<List<Department>>>>() {
            @Override
            public Observable<BaseResponse<List<Department>>> apply(UserBean userBean) throws Exception {
                App.setUserBean(userBean);
                baseView.showLoading("正在获取部门数据……");
                Observable<BaseResponse<List<Department>>> department = loginModel.getDepartment();
                return department;
            }
        }).map(new Function<BaseResponse<List<Department>>, List<Department>>() {
            @Override
            public List<Department> apply(BaseResponse<List<Department>> listBaseResponse) throws Exception {
                if (listBaseResponse.getCode().equals("1")) {
                    if (listBaseResponse.getData()==null){
                        return new ArrayList<>();
                    }
                    return listBaseResponse.getData();
                } else {
                    String msg = listBaseResponse.getMsg();
                    if (TextUtils.isEmpty(msg)) {
                        msg = "获取单位列表失败";
                    }
                    baseView.hideLoading();
                    baseView.showError(msg);
                }
                return null;
            }
        }).filter(new Predicate<List<Department>>() {
            @Override
            public boolean test(List<Department> departments) throws Exception {
                return departments != null;
            }
        });

    }

    public Observable<List<User>> updateUser(Observable<List<Department>> observableDepartment) {


        return observableDepartment.flatMap(new Function<List<Department>, Observable<BaseResponse<List<User>>>>() {
            @Override
            public Observable<BaseResponse<List<User>>> apply(List<Department> departments) throws Exception {
                baseView.showLoading("正在获取人员……");
                DeptDao.getInstance().saveAll(departments);
                Observable<BaseResponse<List<User>>> userList = loginModel.getUserList(App.getUserBean().getId());
                return userList;
            }
        }).map(new Function<BaseResponse<List<User>>, List<User>>() {
            @Override
            public List<User> apply(BaseResponse<List<User>> listBaseResponse) throws Exception {
                if (listBaseResponse.getCode().equals("1")) {
                    if (listBaseResponse.getData()==null){
                        return new ArrayList<User>();
                    }
                    return listBaseResponse.getData();
                } else {
                    String msg = listBaseResponse.getMsg();
                    if (TextUtils.isEmpty(msg)) {
                        msg = "获取人员列表失败";
                    }
                    baseView.hideLoading();
                    baseView.showError(msg);
                }
                return null;
            }
        }).filter(new Predicate<List<User>>() {
            @Override
            public boolean test(List<User> userBeen) throws Exception {
                return userBeen != null;
            }
        });
    }

    public Observable<List<Group>> getGroupList(Observable<List<User>> observableUser) {

        return observableUser.flatMap(new Function<List<User>, Observable<BaseResponse<List<Group>>>>() {
            @Override
            public Observable<BaseResponse<List<Group>>> apply(List<User> users) throws Exception {
                baseView.showLoading("正在群组信息……");

                UserDao.getInstance().saveAll(users);
                Log.d(TAG, "apply: 正在群组信息");
                Observable<BaseResponse<List<Group>>> userList = loginModel.getGroupList(App.getUserBean().getId());
                return userList;
            }
        }).map(new Function<BaseResponse<List<Group>>, List<Group>>() {
            @Override
            public List<Group> apply(BaseResponse<List<Group>> listBaseResponse) throws Exception {
                if (listBaseResponse.getCode().equals("1")) {
                    if (listBaseResponse.getData()==null){
                        return new ArrayList<Group>();
                    }
                    return listBaseResponse.getData();
                } else {
                    String msg = listBaseResponse.getMsg();
                    if (TextUtils.isEmpty(msg)) {
                        msg = "获取群组列表";
                    }
                    baseView.hideLoading();
                    baseView.showError(msg);
                }
                return null;
            }
        }).filter(new Predicate<List<Group>>() {
            @Override
            public boolean test(List<Group> groups) throws Exception {
                return groups!=null;
            }
        });

    }


}
